/** 
 * ================================================================================
 * 		Project		: Kompas Bola
 * 		File		: DetailFragment.java
 * 		Description	: Fragment Detail
 * 		Called		: DetailActivity.java
 * ================================================================================
 * */
package com.kompas.bola.application.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.Log;
import com.kompas.bola.application.R;
import com.kompas.bola.application.CommentActivity;
import com.kompas.bola.application.DetailActivity;
import com.kompas.bola.application.WebActivity;
import com.kompas.bola.application.adapter.ListRelatedAdapter;
import com.kompas.bola.application.dao.Dao;
import com.kompas.bola.application.db.CrudHelper;
import com.kompas.bola.application.model.Content;
import com.kompas.bola.application.model.ContentDetail;
import com.kompas.bola.application.utils.Constants;
import com.kompas.bola.application.utils.ImageLoader;
import com.kompas.bola.application.utils.TimeUtils;
import com.kompas.bola.application.utils.Utils;
/** =========================================================================== */

public class DetailFragment extends Fragment{
	public static final String OFFSET	 	= "offset";
    Content bola							= new Content();
    private int count;
    private int getParam;
	private String guid;
	private byte[] buffer;
	private Intent intent;
	private String getGuid;
	private String getKanal;
	private WebView adBanner;
	private String _getHeadline;
	private WebView contentDesc;
	private ListView list_related;
	private TextView title_detail;
	private WebView imgProgressBar;
	private WebView adBannerBottom;
	private String _getShortenlink;
	private List<String> list_guid;
    private List<String> list_title;
    private ImageLoader imageLoader;
    private ListRelatedAdapter adapter;
	private LinearLayout imageViewLayout;
	private ImageView  thumb_image_detail;
	
	/**
	 * BOOKMARK */
	private String desc						= Constants.EMPTY;
	private String link						= Constants.EMPTY;
	private String title					= Constants.EMPTY;
	private String photo					= Constants.EMPTY;
	private String thumb					= Constants.EMPTY;
	private String kanal					= Constants.EMPTY;
	private String status					= Constants.EMPTY;
	private String pubdate					= Constants.EMPTY;
	
	/** ======================================================================= */
	public DetailFragment(String kanal,String guid, boolean content,int param){
		getKanal							= kanal;
		getGuid								= guid;
		getParam							= param;
	}
	/** ======================================================================= */
	public DetailFragment(){}
	/** ======================================================================= */
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState){
		final View rootView 				= inflater.inflate(R.layout.detail_screen_page, container, false);
		Bundle args 						= getArguments();	
		setHasOptionsMenu(true);			
		
		CrudHelper db						= new CrudHelper(getActivity());	
		
		switch (getParam) {
		
		case Constants.DETAIL_MAIN: //@tbl_bola
			bola							= db.getDetail(args.getInt(OFFSET),getKanal);				
			break;
		case Constants.DETAIL_RELATED: //@tbl_related_bola
			bola							= db.getDetailRelated(args.getInt(OFFSET),getGuid);			
			break;
		case Constants.DETAIL_BOOKMARK: //@tbl_bookmark_bola
			bola							= db.getDetailBookmark(args.getInt(OFFSET));			
			break;

		default:
			break;
		}	

		guid								= bola.getKEY_GUID(); 

		/*progressBar							= (ProgressBar) rootView.findViewById(R.id.progressBar);*/
		imgProgressBar						= (WebView) rootView.findViewById(R.id.imgProgressBar);
		imageViewLayout 					= ((LinearLayout)rootView.findViewById(R.id.thumbnail_detail));
		imageLoader							= new ImageLoader(getActivity().getApplicationContext());
		title_detail						= (TextView) rootView.findViewById(R.id.title_detail);
		thumb_image_detail					= (ImageView) rootView.findViewById(R.id.list_image_detail);
		
		adBanner							= (WebView) rootView.findViewById(R.id.adBanner);
		adBannerBottom						= (WebView) rootView.findViewById(R.id.adBannerBottom);
		
//		String path							= "file:///android_asset/loading.html";
		String path							= "file:///android_asset/loadingdetail.html";
		imgProgressBar.loadUrl(path);	
		imgProgressBar.getSettings().setDefaultZoom(ZoomDensity.FAR);
		imgProgressBar.setVisibility(View.VISIBLE);
		
		adBanner.loadData(Constants.ADS, "text/html", "UTF-8");
		adBannerBottom.loadData(Constants.ADS_TOP, "text/html", "UTF-8");
		
		list_related 						= (ListView) rootView.findViewById(R.id.list_related);	
        contentDesc 						= (WebView) rootView.findViewById(R.id.desc);
		
		/** 
		 * Load Content Detail Task */
		new LoadTask().execute(guid);
		
		// s : Load Basic Template ========= 
		ConnectivityManager conMgr 			= (ConnectivityManager)getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetwork			= conMgr.getActiveNetworkInfo();
	    
	    if(activeNetwork != null && activeNetwork.isConnected()){
			
		    // LOAD TEMPLATE DETAIL       
	        buffer 							= null;
			try {
				InputStream is 				= null;
				try {
					is 						= (getActivity().getAssets().open("kompastemplate.html") != null ? getActivity().getAssets().open("kompastemplate.html") : null);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					is						= null;
					
				}
				int size					= (is != null ? is.available() : 0);
				
				if(size > 0){
					buffer 					= new byte[size];	
					is.read(buffer);	
					is.close();					
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if(buffer != null){				
				String content				= new String(buffer);	

				if(getParam == Constants.DETAIL_MAIN){					
			        List<ContentDetail> bolaDetail	= db.getDetailByGuid(guid);
					
					content					= content.replace("{title}", (bolaDetail.get(0).getTITLE()) != null ? bolaDetail.get(0).getTITLE() : Constants.EMPTY);	
					content					= content.replace("{body}", (bolaDetail.get(0).getPARAGRAPH()) != null ? bolaDetail.get(0).getPARAGRAPH() :  Constants.EMPTY);	
					content					= content.replace("{timestamp}", (bolaDetail.get(0).getDATELINE() != null ? bolaDetail.get(0).getDATELINE() :  Constants.EMPTY)+" WIB");										
				}else{
					content					= content.replace("{title}", (bola.getKEY_TITLE()) != null ? bola.getKEY_TITLE() : Constants.LOADING);	
					content					= content.replace("{body}", Constants.LOADING);
					content					= content.replace("{timestamp}", Constants.EMPTY);
				}
				content						= content.replace("{published_by}", Constants.EMPTY);
				content						= content.replace("{author}", Constants.EMPTY);
				content						= content.replace("{ads_url}", Constants.EMPTY);       			        	

				contentDesc.loadData(content, "text/html", "UTF-8");	        
			}
			
	        adBanner.setVisibility(View.GONE);
	        adBannerBottom.setVisibility(View.GONE);
			contentDesc.setVisibility(View.VISIBLE);
	    }
		// ========= e : Load Basic Template =========
	    
	    list_related.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View convertView, int position,
					long id) {
				// TODO Auto-generated method stub
				Intent detailScreen			= new Intent(getActivity(),DetailActivity.class);
				detailScreen.putExtra(Constants.POSITION, position+1);
 		        detailScreen.putExtra(Constants.GUID, guid);
 		        detailScreen.putExtra(Constants.DETAIL_PARAM, Constants.DETAIL_RELATED);
 		        detailScreen.putExtra(Constants.COUNT_RELATED, count);
 				startActivityForResult(detailScreen, 0);
			}        	
        });
		
		adBanner.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {  
	            intent						= new Intent(getActivity(), WebActivity.class);
	            intent.putExtra(Constants.URL, Constants.ADS_URL);
				startActivityForResult(intent, 0);
	            
               return true;
            }
		});

		adBannerBottom.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {  
	            intent						= new Intent(getActivity(), WebActivity.class);
	            intent.putExtra(Constants.URL, Constants.ADS_URL_BOTTOM);
				startActivityForResult(intent, 0);
               return true;
            }
		});
		
        
		return rootView;		
	}
	/** ======================================================================= */
	public class LoadTask extends AsyncTask<String, Void, ContentDetail>{	 
	    
		@Override
		protected ContentDetail doInBackground(String... params) {
			// TODO Auto-generated method stub
			String guid						= params[0];	
			return (Dao.getDetailContent(guid) != null ? Dao.getDetailContent(guid) : null);
		}		

		@Override	
		protected void onPostExecute(
				ContentDetail result){  
			if(!isCancelled()){					
				NetworkInfo activeNetwork 	= null;
				try {
					ConnectivityManager conMgr 	= (ConnectivityManager)getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);
					activeNetwork 			= conMgr.getActiveNetworkInfo();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					onCancelled();				
					e1.printStackTrace();
				}
			    
				if(result != null){

					if (activeNetwork != null && activeNetwork.isConnected()) {

						getActivity().getActionBar().setTitle(result.getNEWS_TYPE());
						int k 				= getDefaultFontParagraph();	
				    	CrudHelper db		= new CrudHelper(getActivity());
				        

				    	List<ContentDetail> detail	= db.getDetailByGuid(guid);
						try {
							
							title_detail.setText((bola.getKEY_TITLE())!= null  ? bola.getKEY_TITLE() : (detail.get(0).getTITLE()) != null ? detail.get(0).getTITLE() : Constants.EMPTY);
							title_detail.setTextSize(k);
							
							if((result.getSOURCE() != null ? result.getSOURCE() : null) != null || (!(result.getSOURCE() != null ? result.getSOURCE() : Constants.EMPTY).equalsIgnoreCase(Constants.EMPTY))){
								imageViewLayout.setVisibility(View.VISIBLE);
								imageLoader.DisplayImage(result.getSOURCE() != null ? result.getSOURCE() : Constants.EMPTY, thumb_image_detail,Constants.SCALETYPE_CENTER_CROP);							
							}
							
							String content	= Constants.EMPTY;
							
							if(buffer != null){
							    content		= new String(buffer);	
							    
							    content		= content.replace("{title}", Constants.EMPTY);					        
							    content		= content.replace("display:view;", "display:none;");
								
							    switch (getParam) {
								case Constants.DETAIL_MAIN:
									content	= content.replace("{timestamp}", TimeUtils.getTimestampComment(detail.get(0).getDATELINE() != null ? detail.get(0).getDATELINE() : (detail.get(0).getDATELINE() != null ? detail.get(0).getDATELINE() :  Constants.EMPTY)));
									break;
								case Constants.DETAIL_RELATED:
									content	= content.replace("{timestamp}", TimeUtils.getTimestamp(result.getDATELINE() != null ? result.getDATELINE() : (detail.get(0).getDATELINE() != null ? detail.get(0).getDATELINE() :  Constants.EMPTY)));
									break;
								case Constants.DETAIL_BOOKMARK:
									content	= content.replace("{timestamp}", TimeUtils.getTimestamp(result.getDATELINE() != null ? result.getDATELINE() : (detail.get(0).getDATELINE() != null ? detail.get(0).getDATELINE() :  Constants.EMPTY)));
									break;
								default:
									break;
								}					        
							    
							    content		= content.replace("{body}", (result.getPARAGRAPH())!= null  ? result.getPARAGRAPH() : (detail.get(0).getPARAGRAPH()) != null ? detail.get(0).getPARAGRAPH() :  Constants.EMPTY);
							    content		= content.replace("{published_by}", (result.getPUBLISHEDBY()) != null  ? result.getPUBLISHEDBY() : Constants.EMPTY);
							    content		= content.replace("{author}", (result.getAUTHOR())!= null  ? result.getAUTHOR() : Constants.EMPTY);
							    
							    content		= content.replace("{DEFAULT_FONT_PARAGRAPH}", k + "px");
							    contentDesc.loadData(content, "text/html", "UTF-8"); 						
							}
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							Log.e(Constants.ERROR+" Failed get content detail !!!");
						}						
						
						/** GET CONTENT RELATED */
				        list_guid			= Dao.getRelatedContent(result.getLIST_GUID_RELATED());	 
				        list_title			= Dao.getRelatedContent(result.getLIST_TITLE_RELATED());
				    	
						count				= list_guid.size();
						
				    	try {
							if(db.getRelatedByGuid(guid) == 0){
								for(int i=0; i < list_guid.size(); i++){
									ContentDetail bolaDetail	= new ContentDetail();
									bolaDetail.setGUID(guid);
									bolaDetail.setGUID_RELATED(list_guid.get(i));
									bolaDetail.setTITLE_RELATED(list_title.get(i));
									
									/** 
									 * SAVE DATA SQLITE */
									db.createRelated(bolaDetail);
								}							
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				        
				        try {
							adapter 		= new ListRelatedAdapter(getActivity(), list_guid, guid);			        
							list_related.setAdapter(adapter);
					        
					        _getHeadline	= result.getHEAD_LINE();
					        _getShortenlink	= result.getSHORTENLINK();		
					        
					        db.updateContentByGuid(guid,_getShortenlink);
						} catch (Exception e) {
							e.printStackTrace();
							cancel(true);
						} 			   	

						/**
						 * SET VARIABLE BOOKMARK */
				        try {
							title			= (bola.getKEY_TITLE())!= null  ? bola.getKEY_TITLE() : (detail.get(0).getTITLE()) != null ? detail.get(0).getTITLE() : Constants.EMPTY;
							photo			= result.getSOURCE() != null ? result.getSOURCE() : Constants.EMPTY;
							desc			= (result.getPARAGRAPH())!= null  ? result.getPARAGRAPH() : (detail.get(0).getPARAGRAPH()) != null ? detail.get(0).getPARAGRAPH() :  Constants.EMPTY;
							pubdate			= (result.getPUBLISHEDBY()) != null  ? result.getPUBLISHEDBY() : Constants.EMPTY;
							kanal			= result.getNEWS_TYPE();
							link			= result.getSHORTENLINK();
							status			= Constants.BEFORE_READ;
						} catch (Exception e) {
							// TODO Auto-generated catch block
							Log.e(Constants.ERROR+" Failed set Variable Bookmark !!!");
						}
				     }
					
					imgProgressBar.setVisibility(View.GONE);
					adBanner.setVisibility(View.VISIBLE);
					title_detail.setVisibility(View.VISIBLE);
					thumb_image_detail.setVisibility(View.VISIBLE);
					contentDesc.setVisibility(View.VISIBLE);
					list_related.setVisibility(View.VISIBLE);
					adBannerBottom.setVisibility(View.VISIBLE);					
				}
			}
		} 		
	}
	/** =========================================================================== */
    @Override
    public void onResume() {
        super.onResume();
        getActivity().openOptionsMenu();
    }
	/** =========================================================================== */
    @Override
    public void onStop() {
        super.onStop();
		new LoadTask().cancel(true);
    }
	/** =========================================================================== */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.detail_screen_menu, menu);
    }
	/** =========================================================================== */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
        case R.id.action_web:
        	
			if(link.equalsIgnoreCase(Constants.EMPTY)){
				Toast.makeText(getActivity(), Constants.PROCESS, Toast.LENGTH_LONG).show();
				return false;
			}
			
        	intent				= new Intent(getActivity(), WebActivity.class);
            intent.putExtra(Constants.URL, _getShortenlink);
			startActivityForResult(intent, 0);			
            return true;
        case R.id.action_comment:
        	
			if(desc.equalsIgnoreCase(Constants.EMPTY)){
				Toast.makeText(getActivity(), Constants.PROCESS, Toast.LENGTH_LONG).show();
				return false;
			}
			
            intent				= new Intent(getActivity(), CommentActivity.class);
            intent.putExtra(Constants.GUID, guid);
			startActivityForResult(intent, 0);
            return true;
		case R.id.menu_item_share:
			
			if(link.equalsIgnoreCase(Constants.EMPTY)){
				Toast.makeText(getActivity(), Constants.PROCESS, Toast.LENGTH_LONG).show();
				return false;
			}
			
		    String via			= Constants.SHARE_VIA;
			intent 				= new Intent(android.content.Intent.ACTION_SEND);			

			String headline		= _getHeadline;
			String url			= _getShortenlink;
			
			intent.putExtra(Intent.EXTRA_SUBJECT, Constants.KOMPAS_BOLA +"\r\n");
			intent.putExtra(Intent.EXTRA_TEXT, headline+"\r\n"+url+"\r\n\r\n"+via);
			intent.setType("text/plain");
			startActivity(Intent.createChooser(intent, "Share via"));
			return true;
        case R.id.action_bookmark:
        	CrudHelper db		= new CrudHelper(getActivity());
        	status				= db.getStatusByGuid(guid);
            
        	if(status.equalsIgnoreCase(Constants.AFTER_BOOKMARK))
    			Toast.makeText(getActivity(), Constants.SAVE_AFTER_BOOKMARK, Toast.LENGTH_LONG).show();        		
        	else
        		Bookmark();
            return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	/** ======================================================================= */
	private void Bookmark(){
		
    	CrudHelper db			= new CrudHelper(getActivity());
		Content bola			= new Content();		
		
		bola.setKEY_TITLE(title);
		bola.setKEY_PHOTO_URL(photo);
		bola.setKEY_THUMB_URL(Constants.EMPTY);
		bola.setKEY_DESC(desc);
		bola.setKEY_PUB_DATE(pubdate);
		bola.setKEY_GUID(guid);
		bola.setKEY_STATUS(status);
		
		if(title.equalsIgnoreCase(Constants.EMPTY) || title == null){
			Toast.makeText(getActivity(), Constants.PROCESS, Toast.LENGTH_LONG).show();			
		}else{		
	    	db.updateStatusByGuid(guid,Constants.AFTER_BOOKMARK); // Update Status AFTER_BOOKMARK
			db.createBookmark(bola);
			Toast.makeText(getActivity(), Constants.SAVE_BOOKMARK, Toast.LENGTH_LONG).show();			
		}
	}
	/** ======================================================================= */
	private int getScale(){
		return Utils.loadDetailZoom(getActivity().getApplicationContext());
	}
	/** ======================================================================= */
	private int getDefaultFontParagraph(){
		DisplayMetrics dMetrics = new DisplayMetrics();

		final ConnectivityManager conMgr 		= (ConnectivityManager)getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);
	    final NetworkInfo activeNetwork			= conMgr.getActiveNetworkInfo();
	    
		if (activeNetwork != null && activeNetwork.isConnected()) {
			getActivity().getWindowManager().getDefaultDisplay().getMetrics(dMetrics);			
		}
		
	    final float WIDE 		= getActivity().getResources().getDisplayMetrics().widthPixels;
	    int valueWide 			= (int)(WIDE / 32.0f / (dMetrics.scaledDensity));
		
		return valueWide + Constants.FONT_PARAGRAPH * getScale();
	}
	/** ======================================================================= */
}
